package com.keldian.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.keldian.mobilesafe.BuildConfig;
import com.keldian.mobilesafe.R;
import com.keldian.mobilesafe.utils.NumberAddressQueryUtils;
import com.keldian.mobilesafe.utils.SharePrefenceTool;

/**
 * Created by Administrator on 15-12-25.
 */
public class AddressService extends Service {

    private static final String TAG = "AddressService";
    private TelephonyManager tm;
    private MyPhoneStateListener listener;
    private OutCallReceiver outCallReceiver;

    private WindowManager wm;
    private View view;

    private SharedPreferences sp;

    private WindowManager.LayoutParams params;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        outCallReceiver = new OutCallReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(outCallReceiver, filter);

        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        listener = new MyPhoneStateListener();
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        sp = getSharedPreferences("mobilesafe", Context.MODE_PRIVATE);
    }

    //监听电话的响应状态的监听器
    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:

                    String cityName = NumberAddressQueryUtils.queryNumber(incomingNumber);
//                    Toast.makeText(AddressService.this, cityName, Toast.LENGTH_SHORT).show();
                    myToast(cityName);
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (view != null && view.getTag().equals(R.layout.address_show)) {
                        view.setTag("delete");
                        wm.removeView(view);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        listener = null;
        unregisterReceiver(outCallReceiver);
    }


    //监听去电的广播
    private class OutCallReceiver extends BroadcastReceiver {


        private static final String TAG = "OutCallReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "有电话打电话");

            String phone = getResultData();
            String address = NumberAddressQueryUtils.queryNumber(phone);
//            Toast.makeText(context, address, Toast.LENGTH_SHORT).show();
            myToast(address);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                        if (view != null && view.getTag().equals(R.layout.address_show)) {
                            view.setTag("delete");
                            wm.removeView(view);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }

    //自定义Toast样式
    private void myToast(String address) {
        view = View.inflate(this, R.layout.address_show, null);
        view.setTag(R.layout.address_show);
        TextView textview = (TextView) view.findViewById(R.id.tv_address);
        //设置Toast的触摸事件
        view.setOnTouchListener(new View.OnTouchListener() {
            int startX;
            int startY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        Log.i(TAG, "手指摸到控件");
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "手指离开控件");
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putInt("lastX", params.x);
                        editor.putInt("lastY", params.y);
                        editor.commit();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        int newX = (int) event.getRawX();
                        int newY = (int) event.getRawY();
                        int dx = newX - startX;
                        int dy = newY - startY;

                        Log.i(TAG, "手指在控件上移动");
                        params.x += dx;
                        params.y += dy;

                        if (params.x < 0) {
                            params.x = 0;
                        }
                        if (params.y < 0) {
                            params.y = 0;
                        }

                        if (params.x > (wm.getDefaultDisplay().getWidth() - view
                                .getWidth())) {
                            params.x = (wm.getDefaultDisplay().getWidth() - view
                                    .getWidth());
                        }

                        if (params.y > (wm.getDefaultDisplay().getHeight() - view
                                .getHeight())) {
                            params.y = (wm.getDefaultDisplay().getHeight() - view
                                    .getHeight());
                        }
                        wm.updateViewLayout(view, params);


                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        Log.i(TAG, startX + "---" + startY);
                        break;

                    default:
                        break;
                }
                //返回false代表时间未处理完成，true代表处理已完成
                return false;
            }

        });
        //双击后
        final long[] mHits = new long[2];
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHits, 1, mHits, 0, 1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] > (SystemClock.uptimeMillis() - 500)) {
                    Toast.makeText(AddressService.this, "DoubleClick", Toast.LENGTH_SHORT).show();

                    params.x = wm.getDefaultDisplay().getWidth() / 2 - view.getWidth() / 2;
                    params.y = wm.getDefaultDisplay().getHeight() / 2 - view.getHeight() / 2;
                    wm.updateViewLayout(view, params);

                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("lastX", params.x);
                    editor.putInt("lastY", params.y);
                    editor.commit();
                }
            }
        });


        //"半透明","活力橙","卫士蓝","金属灰","苹果绿"
        int[] ids = {R.drawable.call_locate_white, R.drawable.call_locate_orange,
                R.drawable.call_locate_blue
                , R.drawable.call_locate_gray, R.drawable.call_locate_green};

        view.setBackgroundResource(ids[SharePrefenceTool.
                getDialBackgroundIndex(AddressService.this)]);
        textview.setText(address);
        textview.setTextColor(Color.WHITE);
        params = new WindowManager.LayoutParams();
        params.gravity = Gravity.TOP + Gravity.LEFT;
        params.x = sp.getInt("lastX", 100);
        params.y = sp.getInt("lastY", 100);
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;

        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
        wm.addView(view, params);

    }
}
